﻿using ClassLibrary;
using ClassLibrary;
using Manager.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UboxUI;

namespace Manager
{
    public partial class FrmManagerControl : FrmFather
    {
        public FrmManagerControl()
        {
            InitializeComponent();
            #region 視窗初始化

            this.LblTitle.Text = this.Text;
            this.LblTitle2.Text = LblTitle.Text;
            this.BtnClose.Left = this.Width - this.BtnClose.Width - 10;
            this.BtnNarrow.Left = this.BtnClose.Left - this.BtnNarrow.Width - 10;
            this.panel1.Top = 0;
            this.panel2.Top = this.panel1.Height;

            #endregion
        }

        #region 變數設定

        FrmManagerCreate frm = new FrmManagerCreate();

        #endregion
        //分頁未做
        private void FrmManagerControl_Load(object sender, EventArgs e)
        {
            LvManagerdata.View = View.Details;

            CboLevel.DropDownStyle = ComboBoxStyle.DropDownList;

            #region 註冊日期選單設定

            DtpRegistrationdate1.ShowCheckBox = true;
            DtpRegistrationdate1.Checked = false;
            DtpRegistrationdate2.ShowCheckBox = true;
            DtpRegistrationdate2.Checked = false;

            #endregion

            #region SQL 取得管理者資料
            string strsql = @"
                               select manager_username,
                                      manager_first_name,
                                      manager_last_name,
                                      manager_level,
                                      manager_registration_date,
                                      manager_id
                               from Manager 
                            ";
            #endregion

            #region 連線設定

            string strconn = Settings.Default.strConn.ToString();
            SqlConnection conn = new SqlConnection(strconn);

            #endregion

            #region cmd設定
            SqlCommand cmd;
            cmd = new SqlCommand(strsql, conn);
            cmd.CommandType = CommandType.Text;
            #endregion

            #region 執行
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            int i = 1;
            while (dr.Read())
            {
                string labelstring = "";
                switch (Convert.ToInt16(dr["manager_level"]))
                {
                    case 0:
                        labelstring = "資料庫管理員";
                        break;
                    case 1:
                        labelstring = "經理";
                        break;
                    case 2:
                        labelstring = "員工";
                        break;
                }
                DateTime manager_registration_date = Convert.ToDateTime(dr["manager_registration_date"]);
                string manager_registration_date_string =
                string.Format(
                   "{0}-{1}-{2} {3}:{4}",
                   manager_registration_date.Year,
                   manager_registration_date.Month,
                   manager_registration_date.Day,
                   manager_registration_date.Hour,
                   manager_registration_date.Minute
                   );
                string[] list = {
                                   i.ToString(),
                                   Convert.ToString(dr["manager_username"]),
                                   Convert.ToString(dr["manager_first_name"]),
                                   Convert.ToString(dr["manager_last_name"]),
                                   labelstring,
                                   manager_registration_date_string
                               };
                ListViewItem Item = new System.Windows.Forms.ListViewItem(list, -1);
                Item.Tag = Convert.ToString(dr["manager_id"]);
                LvManagerdata.Items.Add(Item);

                i++;
            }
            cmd.Dispose();
            conn.Close();
            conn.Dispose();
            #endregion
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            #region 刪除確認視窗

            MessageBoxButtons buttons = MessageBoxButtons.OKCancel;
            MessageBoxIcon icon = MessageBoxIcon.Question;
            MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button2;
            DialogResult result;
            string m = "確定要刪除嗎";
            string c = "刪除確認";

            #endregion
            if (LvManagerdata.SelectedItems.Count != 0)
            {
                result = MessageBox.Show(m, c, buttons, icon, defaultButton);
                if (result == DialogResult.OK)
                {
                    if (login.name == LvManagerdata.SelectedItems[0].Text)
                    {
                        throw new Exception("無法刪除");
                    }
                    try
                    {
                        #region SQL 刪除管理者
                        string strsql = @"
                                    delete from  manager where manager_id=@Id
                                    set @Check=@@ROWCOUNT
                                 ";

                        #endregion

                        #region 連線設定

                        string strconn = Settings.Default.strConn.ToString();
                        SqlConnection conn = new SqlConnection(strconn);

                        #endregion

                        #region cmd設定
                        SqlCommand cmd;
                        cmd = new SqlCommand(strsql, conn);
                        cmd.CommandType = CommandType.Text;
                        #endregion

                        #region Input變數
                        SqlParameter Id = new SqlParameter("@Id", SqlDbType.Int, 20);
                        Id.Direction = ParameterDirection.Input;
                        Id.Value = this.LvManagerdata.SelectedItems[0].Tag;
                        cmd.Parameters.Add(Id);
                        #endregion

                        #region Output變數
                        SqlParameter check = new SqlParameter("@Check", SqlDbType.Int, 1);
                        check.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add(check);
                        #endregion

                        #region 執行
                        try
                        {
                            conn.Open();
                            cmd.ExecuteNonQuery();
                        }
                        catch
                        {
                            throw new Exception("刪除失敗");
                        }
                        cmd.Dispose();
                        conn.Close();
                        #endregion

                        #region 更新LvManagerdata

                        LvManagerdata.Items.Clear();
                        FrmManagerControl_Load(sender, e);
                        int checkDelete = Convert.ToInt32(cmd.Parameters["@Check"].Value);
                        if (checkDelete > 0)
                        {
                            throw new Exception("刪除成功");
                        }
                        else
                        {
                            throw new Exception("刪除失敗");
                        }

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }  
            }
            else
            {
                MessageBox.Show("請選擇刪除對象");
            }
        }

        private void Btninsert_Click(object sender, EventArgs e)
        {
            frm = new FrmManagerCreate();
            frm.ShowDialog();
            LvManagerdata.Items.Clear();
            FrmManagerControl_Load(sender, e);
        }

        private void BtnSelect_Click(object sender, EventArgs e)
        {
            int selectnum = 0;
            LvManagerdata.Items.Clear();
            #region SQL 取得管理者資料
            string strsql = @"
                               select manager_username,
                                      manager_first_name,
                                      manager_last_name,
                                      manager_level,
                                      manager_registration_date,
                                      manager_id
                               from Manager
                            ";
            #region 條件判斷
            if (
                (TxtUsername.Text != "") ||
                (TxtFirstname.Text != "") ||
                (TxtLastname.Text != "") ||
                ((CboLevel.SelectedIndex != -1)&&(CboLevel.SelectedIndex !=3)) ||
                (DtpRegistrationdate1.Checked == true)||
                (DtpRegistrationdate2.Checked == true)
                )
            {
                strsql += " WHERE ";
            }
            if(TxtUsername.Text!="")
            {
                strsql += " manager_username like('%'+@Username+'%')";
                selectnum++;
            }
            if (TxtFirstname.Text != "")
            {
                if (selectnum > 0) 
                {
                    strsql += " AND ";
                }
                strsql += " manager_first_name like('%'+@Firstname+'%')";
                selectnum++;
            }
            if (TxtLastname.Text!= "")
            {
                if (selectnum > 0)
                {
                    strsql += " AND ";
                }
                strsql += " manager_last_name like('%'+@Lastname+'%')";
                selectnum++;
            }
            if ((CboLevel.SelectedIndex != -1)&&(CboLevel.SelectedIndex != 3))
            {
                if (selectnum > 0)
                {
                    strsql += " AND ";
                }
                strsql += " manager_level like('%'+@Level+'%')";
                selectnum++;
            }
            if ((DtpRegistrationdate1.Checked == true) && (DtpRegistrationdate2.Checked == true))
            {
                if (selectnum > 0)
                {
                    strsql += " AND ";
                }
                strsql += "manager_registration_date BETWEEN @Registration_date1  AND  @Registration_date2";
            }
            else if (DtpRegistrationdate1.Checked == true)
            {
                if (selectnum > 0)
                {
                    strsql += " AND ";
                }
                strsql += "manager_registration_date BETWEEN @Registration_date1  AND  @Registration_date2";
            }
            else if (DtpRegistrationdate2.Checked == true)
            {
                if (selectnum > 0)
                {
                    strsql += " AND ";
                }
                strsql += "manager_registration_date BETWEEN @Registration_date1  AND  @Registration_date2";
            }
            #endregion

            #endregion

            #region 連線設定

            string strconn = Settings.Default.strConn.ToString();
            SqlConnection conn = new SqlConnection(strconn);

            #endregion

            #region cmd設定
            SqlCommand cmd;
            cmd = new SqlCommand(strsql, conn);
            cmd.CommandType = CommandType.Text;
            #endregion

            #region Input變數

            if (TxtUsername.Text != "") 
            {
                SqlParameter Username = new SqlParameter("@Username", SqlDbType.NVarChar, 20);
                Username.Direction = ParameterDirection.Input;
                Username.Value = this.TxtUsername.Text;
                cmd.Parameters.Add(Username);
            }
            if (TxtFirstname.Text != "")
            {
                SqlParameter Firstname = new SqlParameter("@Firstname", SqlDbType.NVarChar, 10);
                Firstname.Direction = ParameterDirection.Input;
                Firstname.Value = this.TxtFirstname.Text;
                cmd.Parameters.Add(Firstname);
            }
            if (TxtLastname.Text != "")
            {
                SqlParameter Lastname = new SqlParameter("@Lastname", SqlDbType.NVarChar, 10);
                Lastname.Direction = ParameterDirection.Input;
                Lastname.Value = this.TxtLastname.Text;
                cmd.Parameters.Add(Lastname);
            }

            if (CboLevel.SelectedIndex != -1)
            {
                SqlParameter Level = new SqlParameter("@Level", SqlDbType.Char, 1);
                Level.Direction = ParameterDirection.Input;
                Level.Value = CboLevel.SelectedIndex;
                cmd.Parameters.Add(Level);
            }
            #region 日期參數
            if ((DtpRegistrationdate1.Checked == true) && (DtpRegistrationdate2.Checked == true))
            {
                SqlParameter Registration_date = new SqlParameter("@Registration_date1", SqlDbType.DateTime, 20);
                Registration_date.Direction = ParameterDirection.Input;
                Registration_date.Value = 
                    string.Format(
                    "{0}-{1}-{2} 00:00:00.000",
                    DtpRegistrationdate1.Value.Year,
                    DtpRegistrationdate1.Value.Month,
                    DtpRegistrationdate1.Value.Day
                    );
                cmd.Parameters.Add(Registration_date);

                SqlParameter Registration_date2 = new SqlParameter("@Registration_date2", SqlDbType.DateTime, 20);
                Registration_date2.Direction = ParameterDirection.Input;
                Registration_date2.Value =
                   string.Format(
                   "{0}-{1}-{2} 23:59:59.999",
                   DtpRegistrationdate2.Value.Year,
                   DtpRegistrationdate2.Value.Month,
                   DtpRegistrationdate2.Value.Day
                   );
                cmd.Parameters.Add(Registration_date2);
            }
            else if ((DtpRegistrationdate1.Checked == true))
            {
                SqlParameter Registration_date = new SqlParameter("@Registration_date1", SqlDbType.DateTime, 20);
                Registration_date.Direction = ParameterDirection.Input;
                Registration_date.Value =
                    string.Format(
                    "{0}-{1}-{2} 00:00:00.000",
                    DtpRegistrationdate1.Value.Year,
                    DtpRegistrationdate1.Value.Month,
                    DtpRegistrationdate1.Value.Day
                    );
                cmd.Parameters.Add(Registration_date);

                SqlParameter Registration_date2 = new SqlParameter("@Registration_date2", SqlDbType.DateTime, 20);
                Registration_date2.Direction = ParameterDirection.Input;
                Registration_date2.Value =
                   string.Format(
                   "{0}-{1}-{2} 23:59:59.999",
                   DtpRegistrationdate1.Value.Year,
                   DtpRegistrationdate1.Value.Month,
                   DtpRegistrationdate1.Value.Day
                   );
                cmd.Parameters.Add(Registration_date2);
            }
            else if ((DtpRegistrationdate2.Checked == true))
            {
                SqlParameter Registration_date = new SqlParameter("@Registration_date1", SqlDbType.DateTime, 20);
                Registration_date.Direction = ParameterDirection.Input;
                Registration_date.Value =
                    string.Format(
                    "{0}-{1}-{2} 00:00:00.000",
                    DtpRegistrationdate2.Value.Year,
                    DtpRegistrationdate2.Value.Month,
                    DtpRegistrationdate2.Value.Day
                    );
                cmd.Parameters.Add(Registration_date);

                SqlParameter Registration_date2 = new SqlParameter("@Registration_date2", SqlDbType.DateTime, 20);
                Registration_date2.Direction = ParameterDirection.Input;
                Registration_date2.Value =
                   string.Format(
                   "{0}-{1}-{2} 23:59:59.999",
                   DtpRegistrationdate2.Value.Year,
                   DtpRegistrationdate2.Value.Month,
                   DtpRegistrationdate2.Value.Day
                   );
                cmd.Parameters.Add(Registration_date2);
            }
            #endregion

            #endregion

            #region 執行
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            int i = 1;
            while (dr.Read())
            {
                string labelstring = "";
                switch (Convert.ToInt16(dr["manager_level"]))
                {
                    case 0:
                        labelstring = "資料庫管理員";
                        break;
                    case 1:
                        labelstring = "經理";
                        break;
                    case 2:
                        labelstring = "員工";
                        break;
                }
                DateTime manager_registration_date =Convert.ToDateTime(dr["manager_registration_date"]);
                string manager_registration_date_string=     
                string.Format(
                   "{0}-{1}-{2} {3}:{4}",
                   manager_registration_date.Year,
                   manager_registration_date.Month,
                   manager_registration_date.Day,
                   manager_registration_date.Hour,
                   manager_registration_date.Minute
                   );
                    Convert.ToDateTime(dr["manager_registration_date"]);
                string[] list = {
                                   i.ToString(),
                                   Convert.ToString(dr["manager_username"]),
                                   Convert.ToString(dr["manager_first_name"]),
                                   Convert.ToString(dr["manager_last_name"]),
                                   labelstring,
                                   manager_registration_date_string
                               };
                ListViewItem Item = new System.Windows.Forms.ListViewItem(list, -1);
                Item.Tag = Convert.ToString(dr["manager_id"]);
                LvManagerdata.Items.Add(Item);

                i++;
            }
            cmd.Dispose();
            conn.Close();
            conn.Dispose();
            #endregion

        }

        #region 日期選單判斷

        private void DtpRegistrationdate1_ValueChanged(object sender, EventArgs e)
        {
            if ((this.DtpRegistrationdate2.Value < this.DtpRegistrationdate1.Value) && (this.DtpRegistrationdate2.Checked == true))
            {
                this.DtpRegistrationdate1.Value = this.DtpRegistrationdate2.Value.AddDays(-1);
                MessageBox.Show("日期不可比結束日期之後");
            }
        }

        private void DtpRegistrationdate2_ValueChanged(object sender, EventArgs e)
        {
            if ((this.DtpRegistrationdate2.Value < this.DtpRegistrationdate1.Value)&&(this.DtpRegistrationdate1.Checked==true))
            {
                this.DtpRegistrationdate2.Value = this.DtpRegistrationdate1.Value.AddDays(1);
                MessageBox.Show("日期不可比起始日期更之前");
            }
        }

        #endregion

        #region 判斷輸入是否有空格

        private void TxtUsername_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == ' ')
                {
                    e.Handled = true;
                    throw new Exception("不能輸入空白");
                }/*寫在KeyDown無效*/
            }
            catch (Exception ex)
            {
                MessageBox.Show( ex.Message);
            }
        }

        private void TxtFirstname_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == ' ')
                {
                    e.Handled = true;
                    throw new Exception("不能輸入空白");
                }/*寫在KeyDown無效*/
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void TxtLastname_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == ' ')
                {
                    e.Handled = true;
                    throw new Exception("不能輸入空白");
                }/*寫在KeyDown無效*/
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion


        #region 按鈕的樣式



        private void Btninsert_MouseEnter(object sender, EventArgs e)
        {
            this.Btninsert.FlatAppearance.BorderSize = 0;
            this.Btninsert.ForeColor = Color.White;
        }

        private void Btninsert_MouseLeave(object sender, EventArgs e)
        {
            this.Btninsert.FlatAppearance.BorderSize = 1;
            this.Btninsert.ForeColor = Color.Black;
        }

        private void BtnSelect_MouseEnter(object sender, EventArgs e)
        {
            this.BtnSelect.FlatAppearance.BorderSize = 0;
            this.BtnSelect.ForeColor = Color.White;
        }

        private void BtnSelect_MouseLeave(object sender, EventArgs e)
        {
            this.BtnSelect.FlatAppearance.BorderSize = 1;
            this.BtnSelect.ForeColor = Color.Black;
        }
       

        private void BtnDelete_MouseEnter(object sender, EventArgs e)
        {
            this.BtnDelete.FlatAppearance.BorderSize = 0;
            this.BtnDelete.ForeColor = Color.White;
        }

        private void BtnDelete_MouseLeave(object sender, EventArgs e)
        {
            this.BtnDelete.FlatAppearance.BorderSize = 1;
            this.BtnDelete.ForeColor = Color.Black;
        } 
        
        #endregion
    }
}
